<template>
  <el-drawer
    :title="copName"
    size="60%"
    :visible.sync="isShowModal"
    @close="closeDrawer"
  >
    <!-- <div class="app-main-title">{{ copName }} <div class="goback" @click="$router.replace(`/vipCardList/vipCardList`)">
      <i class="el-icon-refresh-left" /> {{translate('backPage')}}
    </div></div> -->
    <div>
      <el-form
        ref="form"
        class="doumee-form"
        :model="param"
        label-width="auto"
        label-suffix="："
        :rules="rules"
      >
        <div class="property-title">{{ translate("membercardProp") }}</div>
        <el-form-item :label="translate('membercardName')" prop="cardName">
          <el-input
            v-model="param.cardName"
            maxlength="6"
            :placeholder="translate('membercardNamePlace')"
            style="width: 400px"
          />
          <span class="placeholder9 ml20">{{
            translate("membercardNameP")
          }}</span>
        </el-form-item>
        <el-form-item
          :label="translate('ky')"
          class="select-style"
          prop="avatar"
          :rules="{
            required: true,
            message:
              param.cardCode == 'cardZero'
                ? translate('qscky')
                : translate('qxzky'),
            trigger: 'change',
          }"
        >
          <el-radio-group v-model="param.cardCode" @change="changeType">
            <el-radio
              v-for="(item, index) in memberImgList"
              :key="index"
              :label="item.code"
            >{{ item.remaks }}</el-radio>
          </el-radio-group>
          <transition name="fade">
            <Cropper
              v-if="dialogCropperVisible"
              :option-img="optionImg"
              :fileinfo="fileinfo"
              use-type="CARD_TYPE_IMG"
              :fixed-number="[69, 34]"
              @formSubmit="cropperSubmit"
              @formClose="cropperClose"
            />
          </transition>
          <div class="upload-wrap">
            <el-upload
              v-if="param.cardCode == 'cardZero'"
              class="device-uploader"
              :action="uploadFileUrl"
              :data="uploadParam"
              :show-file-list="false"
              accept=".jpg,.png,.jpeg"
              :auto-upload="false"
              :on-change="addFileChange"
            >
              <i class="el-icon-plus uploader-icon" />
              <div
                v-if="!param.showAvatar"
                style="color: #999999; font-size: 14px; line-height: 20px"
              >
                {{ translate("uploadPic") }}
              </div>
              <div
                v-show="param.showAvatar"
                class="file"
                :style="'background-image: url(' + param.showAvatar + ')'"
              >
                <div class="delete">
                  <i class="el-icon-delete icon" @click.stop="deleteImage" />
                </div>
              </div>
            </el-upload>
            <div
              v-if="param.cardCode == 'cardZero'"
              class="placeholader tip-style"
            >
              <div class="placeholader9">
                {{ translate("jycc") }}：690px*334px
              </div>
              <div>
                {{ translate("zctpsm") }}
              </div>
            </div>
          </div>
          <el-image
            v-if="param.cardCode != 'cardZero' && param.showAvatar"
            style="width: 174px; height: 84px"
            :src="param.showAvatar"
            :preview-src-list="[param.showAvatar]"
          />
        </el-form-item>
        <el-form-item :label="translate('saleChannel')" prop="channelList">
          <el-checkbox-group v-model="param.channelList">
            <el-checkbox :label="translate('wechatDuan')" />
            <el-checkbox :label="translate('venueDuan')" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item :label="translate('morenkaka')">
          <el-switch
            v-model="isNormal"
            active-color="#435EBE"
            inactive-color="#999999"
          />
          <span class="tip-style">{{ translate("morenkakaP") }}</span>
        </el-form-item>
        <el-form-item :label="translate('level')">
          <el-input
            v-model="param.level"
            oninput="value=value.replace(/[^\d]/g,'')"
            :placeholder="translate('setmemberLevelP')"
            style="width: 400px"
          />
          <span class="tip-style">{{ translate("setmemberLevelP") }}</span>
        </el-form-item>

        <div class="line-style" />

        <div class="property-title">{{ translate("ruleSet") }}</div>

        <el-form-item
          :label="translate('shouchongMini')"
          prop="price"
          class="discount-style"
        >
          <el-input
            v-model="param.price"
            oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,2})?).*$/g, '$1')"
            :placeholder="translate('shouchongMiniP')"
          />
        </el-form-item>
        <el-form-item
          :label="translate('xuchongMini')"
          prop="continuedPrice"
          class="discount-style"
        >
          <el-input
            v-model="param.continuedPrice"
            oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,2})?).*$/g, '$1')"
            :placeholder="translate('xuchongMiniP')"
          />
        </el-form-item>
        <el-form-item :label="translate('autoShengjiKa')">
          <el-switch
            v-model="upgrade"
            active-color="#435EBE"
            inactive-color="#999999"
          />
          <span class="tip-style">{{ translate("autoShengjiMem") }}</span>
        </el-form-item>
        <el-form-item
          v-if="upgrade"
          :label="translate('leijiShengji')"
          prop="totalMoney"
        >
          <el-input
            v-model="param.totalMoney"
            oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,2})?).*$/g, '$1')"
            :placeholder="translate('leijiShengjiP')"
            style="width: 400px"
          />
        </el-form-item>

        <div class="line-style" />

        <div class="property-title">
          {{ translate("discountInfoSet") }}
          <span class="tip-style">{{ translate("qsrmrzk") }}</span>
        </div>

        <el-form-item
          v-for="(item, index) in param.discounts"
          :key="index"
          :label="item.discountTypeName"
          :prop="`discounts[${index}].discount`"
          :rules="{
            required: true,
            message: translate('qsrspzk'),
            trigger: 'blur',
          }"
          class="discount-style"
        >
          <el-input
            v-model="item.discount"
            onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
            oninput="if(value<0||value>1) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}"
            :placeholder="translate('qsrspzkMr')"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            v-preventReClick
            type="primary"
            :loading="loading"
            @click="onSubmit('form')"
          >{{ translate("tj") }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-drawer>
</template>

<script>
import { addCard, cardDetail, updateCard, uploadFile, discountType, mrMemberImg } from '@/api'
import Cropper from '@/components/cropper'
// import { getList } from '@/api/table'
export default {
  components: {
    Cropper
  },
  data() {
    return {
      isShowModal: false,

      optionImg: '',
      fileinfo: {},
      dialogCropperVisible: false,
      loadProgress: 0, // 动态显示进度条
      progressFlag: false, // 关闭进度条
      copName: this.translate('memberCardAdd'),
      avatarStyle: 0,
      avatarStyles: [],
      channelList: [],
      upgrade: false,
      loading: false,
      isNormal: false,
      imageList: [],
      uploadFileUrl: uploadFile,
      dialogVisible: false,
      memberImgList: [],
      uploadParam: {
        // folder: 'PUBLIC_IMG'
        folder: 'CARD_TYPE_IMG'
      },
      param: {
        channelList: [],
        discounts: [
          {
            discount: '',
            discountType: '10',
            id: ''
          },
          {
            discount: '',
            discountType: '20',
            id: ''
          },
          {
            discount: '',
            discountType: '30',
            id: ''
          },
          {
            discount: '',
            discountType: '40',
            id: ''
          }
        ],
        isnormal: '',
        price: '',
        totalMoney: '',
        cardName: '',
        upgrade: ''
      },
      rules: {
        cardName: [
          { required: true, message: this.translate('qsr'), trigger: 'blur' }
        ],
        simpleName: [
          { required: true, message: this.translate('qsr'), trigger: 'blur' }
        ],
        channelList: [
          { required: true, message: this.translate('qxz'), trigger: 'change' }
        ],
        avatar: [
          { required: true, message: this.translate('qsc'), trigger: 'change' }
        ],
        price: [
          { required: true, message: this.translate('qsr'), trigger: 'blur' }
          // { pattern:
          //     /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '金额必须大于0', trigger: 'blur' }
        ],
        continuedPrice: [
          { required: true, message: this.translate('qsr'), trigger: 'blur' }
          // { pattern:
          //     /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '金额必须大于0', trigger: 'blur' }
        ],
        totalMoney: [
          { required: true, message: this.translate('qsr'), trigger: 'blur' },
          {
            pattern:
              /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: this.translate('jebxdy0'), trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getMrMemberImg()
  },
  methods: {
    // 默认卡样式
    getMrMemberImg() {
      mrMemberImg({ param: {}}).then(res => {
        if (res.errorCode === '000000') {
          this.memberImgList = res.recordList || []
          if (!this.$route.query.id && this.memberImgList.length > 0) {
            this.$set(this.param, 'cardCode', res.recordList[0].code)
            this.$set(this.param, 'avatar', res.recordList[0].pic)
            this.$set(this.param, 'showAvatar', res.recordList[0].showPic)
          }
        }
      })
    },
    getStyle() {
      discountType({
        param: {},
        userId: sessionStorage.getItem('userId')
      }).then(res => {
        console.log(res)
        this.param.discounts = res.recordList
        const oldDiscount = this.param.discounts
        for (let index = 0; index < 4; index++) {
          for (var j = 0; j < 3; j++) {
            if (parseInt(oldDiscount[j].discountType) > parseInt(oldDiscount[j + 1].discountType)) {
              var temp = oldDiscount[j]
              oldDiscount[j] = oldDiscount[j + 1]
              oldDiscount[j + 1] = temp
            }
          }
        }
        this.param.discounts = oldDiscount
      }).catch(err => {
        console.log(err)
      })
    },
    closeDrawer() {
      this.isShowModal = false
      this.$emit('close')
    },
    getCardDetail(id) {
      cardDetail({
        param: { id: id },
        userId: sessionStorage.getItem('userId')
      }).then(res => {
        this.param = res.record
        console.log(this.param)
        switch (this.param.channel) {
          case '1_1':
            this.$set(this.param, 'channelList', [this.translate('wechatDuan'), this.translate('cgpcd')])
            break
          case '0_1':
            this.$set(this.param, 'channelList', [this.translate('cgpcd')])
            break
          case '1_0':
            this.$set(this.param, 'channelList', [this.translate('wechatDuan')])
            break
          default:
            break
        }
        this.upgrade = this.param.upgrade === '1'
        this.isNormal = this.param.isnormal === '1'

        this.imageList.push({
          url: this.param.showAvatar,
          response: {
            insertUrl: this.param.avatar,
            showUrl: this.param.showAvatar
          }
        })
        if (!this.param.discounts.length) {
          // 添加折扣
          for (let index = 0; index < 4; index++) {
            this.param.discounts.push({
              discount: '',
              discountType: (10 * (index + 1)).toString(),
              id: ''
            })
          }
        } else {
          // 折扣排序
          const oldDiscount = this.param.discounts
          for (let index = 0; index < 4; index++) {
            for (var j = 0; j < 3; j++) {
              if (parseInt(oldDiscount[j].discountType) > parseInt(oldDiscount[j + 1].discountType)) {
                var temp = oldDiscount[j]
                oldDiscount[j] = oldDiscount[j + 1]
                oldDiscount[j + 1] = temp
              }
            }
          }
          this.param.discounts = oldDiscount
          console.log(this.param.discounts)
        }
      })
    },
    handleAvatarSuccess(res, file) {
      this.$set(this.param, 'avatar', res.insertUrl)
      this.$set(this.param, 'showAvatar', res.showUrl)
      this.$refs.form.clearValidate()
    },
    changeType(e) {
      if (e === 'cardZero') {
        this.$set(this.param, 'avatar', '')
        this.$set(this.param, 'showAvatar', '')
      } else {
        const arr = this.memberImgList
        arr.forEach(s => {
          if (s.code === e) {
            this.$set(this.param, 'avatar', s.pic)
            this.$set(this.param, 'showAvatar', s.showPic)
          }
        })
      }
      this.$refs.form.clearValidate()
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'showAvatar', config.showUrl)
        this.$set(this.param, 'avatar', config.insertUrl)
        this.dialogCropperVisible = false
        this.$refs.form.clearValidate()
      } else {
        this.$message.error(config.msg || this.translate('scsb'))
        this.$refs.form.clearValidate()
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      // this.files = file.raw;
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 删除头像
    deleteImage() {
      this.$set(this.param, 'avatar', '')
      this.$set(this.param, 'showAvatar', '')
    },
    remoImageUrl(file, fileList) {
      console.log(file, fileList)
      this.$set(this.param, 'avatar', '')
      this.$set(this.param, 'showAvatar', '')
    },
    onSubmit(formName) {
      const that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.loading = true
          switch (that.param.channelList.length) {
            case 0:
              that.$message.error(this.translate('zsxzyzxsqd'))
              return
            case 1:
              if (that.param.channelList[0] === this.translate('wechatDuan')) {
                that.param.channel = '1_0'
              } else {
                that.param.channel = '0_1'
              }
              break
            case 2:
              that.param.channel = '1_1'
              break
            default:
              break
          }
          that.param.isnormal = that.isNormal ? '1' : '0'
          that.param.continuedPrice = parseFloat(that.param.continuedPrice)
          that.param.upgrade = that.upgrade ? '1' : '0'
          if (that.upgrade) {
            that.param.totalMoney = parseFloat(that.param.totalMoney)
          }
          const dcArr = that.param.discounts
          dcArr.forEach(temp => {
            temp.discount = parseFloat(temp.discount)
          })
          that.param.discounts = dcArr
          if (that.param.id) {
            const p = that.param
            p.id = that.param.id
            updateCard({ param: p }).then(res => {
              that.loading = false
              if (res.errorCode === '000000') {
                console.log(res.errorMsg)
                that.$message.success(this.translate('courseBmcg'))
                this.closeDrawer()
                this.$emit('success')
              }
            }).catch(er => {
              that.loading = false
              console.log(er)
            })
          } else {
            addCard({ param: that.param }).then(res => {
              this.loading = false
              if (res.errorCode === '000000') {
                console.log(res.errorMsg)
                that.$message.success(this.translate('addScs'))
                this.closeDrawer()
                this.$emit('success')
              }
            }).catch(er => {
              this.loading = false
              console.log(er)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.device-uploader {
  width: 174px;
  height: 84px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.select-style {
  vertical-align: middle;
}
.upload-style {
  vertical-align: middle;
  display: inline-block;
  border: none;
  position: relative;
  .deleget {
    position: absolute;
    right: 0px;
  }
}

.img-style {
  margin: auto;
  background-color: #eee;
  width: 100px;
  height: 60px;
  vertical-align: middle;
}
.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
.line-style {
  background-color: #dfe2e8;
  height: 1px;
  // width: 80%;
  // margin: 0 auto;
  margin-bottom: 20px;
}
.discount-style {
  width: 50%;
  display: inline-block;
}
.upload-wrap {
  display: flex;
  align-items: center;
  .placeholader {
    flex: 1;
    div {
      line-height: 20px;
    }
  }
}
</style>
